﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace BulldogCMS.Data.Security
{
    public class XMLSecurityTreeProvider : ISecurityTreeProvider
    {
        private XDocument _securityXdoc = null;
        private List<IPartialUserNode> _partialUserNodes = null;
        private List<IPartialGroupNode> _partialGroupNodes = null;

        public XMLSecurityTreeProvider(XDocument securityXdoc)
        {
            this._securityXdoc = securityXdoc;
        }

        public IEnumerable<IPartialUserNode> PartialUserNodes
        {
            get
            {
                if (this._partialUserNodes == null)
                {
                    this._partialUserNodes = this.LoadPartialUserNodes();
                }
                return this._partialUserNodes;
            }
        }

        public IEnumerable<IPartialGroupNode> PartialGroupNodes
        {
            get {
                if (this._partialGroupNodes == null)
                {
                    this._partialGroupNodes = this.LoadPartialGroupNodes();
                }
                return this._partialGroupNodes;
            }
        }

        private List<IPartialUserNode> LoadPartialUserNodes()
        {
            List<IPartialUserNode> list = new List<IPartialUserNode>();
            if (this._securityXdoc != null && this._securityXdoc.Root != null && this._securityXdoc.Root.Element("users") != null)
            {
                foreach (var userEl in this._securityXdoc.Root.Element("users").Elements("user"))
                {
                    XMLPartialUserNode partialNode = new XMLPartialUserNode(userEl);
                    list.Add(partialNode);
                }
            }
            return list;
        }

        private List<IPartialGroupNode> LoadPartialGroupNodes()
        {
            List<IPartialGroupNode> list = new List<IPartialGroupNode>();
            if (this._securityXdoc != null && this._securityXdoc.Root != null && this._securityXdoc.Root.Element("groups") != null)
            {
                foreach (var groupEl in this._securityXdoc.Root.Element("users").Elements("group"))
                {
                    XMLPartialGroupNode partialNode = new XMLPartialGroupNode(groupEl);
                    list.Add(partialNode);
                }
            }
            return list;
        }



    }
}
